package com.sdwz.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Strings;
import com.sdwz.commonutil.exception.LibraryException;
import com.sdwz.serviceutil.utils.JwtUtil;
import com.sdwz.serviceutil.utils.MD5;
import com.sdwz.user.entity.BorrowCardInfo;
import com.sdwz.user.entity.StuInfo;
import com.sdwz.user.entity.UserInfo;
import com.sdwz.user.entity.vo.AuthVo;
import com.sdwz.user.entity.vo.BorrowCardInfoVo;
import com.sdwz.user.entity.vo.RegisterVo;
import com.sdwz.user.entity.vo.UserInfoVo;
import com.sdwz.user.mapper.UserInfoMapper;
import com.sdwz.user.service.BorrowCardInfoService;
import com.sdwz.user.service.StuInfoService;
import com.sdwz.user.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-03-26
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    BorrowCardInfoService borrowCardInfoService;

    @Autowired
    StuInfoService stuInfoService;

    /**
     * 注册账户
     * @param registerVo
     */
    @Override
    public void register(RegisterVo registerVo) {
        System.out.println(registerVo.toString());
        String nickName = registerVo.getNickname();
        String phone = registerVo.getMobile();
        String password = registerVo.getPassword();
        String code = registerVo.getCode();

        if (Strings.isNullOrEmpty(nickName) || Strings.isNullOrEmpty(phone) ||
        Strings.isNullOrEmpty(password) || Strings.isNullOrEmpty(code)){
            throw new LibraryException(201,"注册失败");
        }

        //判断当前手机号是否注册过
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",phone);
        Integer count = baseMapper.selectCount(wrapper);
        if (count>0){
            throw new LibraryException(201,"该号码已注册");
        }

        //检查验证码
        String redisCode = redisTemplate.opsForValue().get(phone);

        if (!redisCode.equals(code)) {
            throw new LibraryException(201,"验证码错误");
        }

        UserInfo userInfo = new UserInfo();
        String pwd = MD5.encrypt(password);
        userInfo.setNickName(nickName);
        userInfo.setPhone(phone);
        userInfo.setPassword(pwd);
        userInfo.setStatus(0);

        baseMapper.insert(userInfo);

    }

    /**
     * 登录账户，返回令牌
     * @param userInfo
     * @return
     */
    @Override
    public Map<String, String> login(UserInfo userInfo) {
        String phone = userInfo.getPhone();
        String password = userInfo.getPassword();

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",phone);
        UserInfo user = baseMapper.selectOne(wrapper);
        if (user == null){
            throw new LibraryException(201,"账户不存在");
        }

        if (user.getPassword().equals(MD5.encrypt(password))){
            Map<String,String> result = new HashMap<>();
            result.put("name",user.getNickName());
            result.put("token",JwtUtil.createToken(Long.parseLong(user.getId()),user.getNickName()));
            return result;
        }else {
            throw new LibraryException(201,"密码错误");
        }
    }

    /**
     * 申请认证
     * @param userId
     * @param authVo
     */
    @Override
    public void certificate(String userId, AuthVo authVo) {
        StuInfo stuInfo = new StuInfo();
        BorrowCardInfo borrowCardInfo = new BorrowCardInfo();
        BeanUtils.copyProperties(authVo,stuInfo);
        BeanUtils.copyProperties(authVo,borrowCardInfo);

        //如果userId不同，证件类型和证件编号相同，并且状态为认证成功（2），提醒当前证件已绑定
        //通过证件编号和证件类型检查是否绑定过
        String certificatesNo = borrowCardInfo.getCertificatesNo();
        String certificatesType = borrowCardInfo.getCertificatesType();
        QueryWrapper<BorrowCardInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("certificates_type",certificatesType);
        wrapper.eq("certificates_no",certificatesNo);
        wrapper.eq("auth_status",2);
        int count = borrowCardInfoService.count(wrapper);
        if (count>0){
            throw new LibraryException(201,"绑定错误：当前证件已绑定");
        }
        borrowCardInfo.setUserId(userId);
        borrowCardInfo.setAuthStatus(1);
        borrowCardInfo.setStatus(1);
        borrowCardInfo.setBorrowNumber(10);
        borrowCardInfoService.save(borrowCardInfo);

        stuInfo.setUserId(userId);
        stuInfo.setStuNo(certificatesNo);
        stuInfoService.save(stuInfo);

        //为用户表用户添加姓名
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setStatus(1);
        userInfo.setName(stuInfo.getStuName());
        baseMapper.updateById(userInfo);

    }

    /**
     * 查看实名信息
     * @param userId
     * @return
     */
    @Override
    public AuthVo getCertificateInfo(String userId) {
        AuthVo result = new AuthVo();
        QueryWrapper<BorrowCardInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        BorrowCardInfo borrowCardInfo = borrowCardInfoService.getOne(wrapper);

        QueryWrapper<StuInfo> stuWrapper = new QueryWrapper<>();
        stuWrapper.eq("user_id",userId);
        StuInfo stuInfo = stuInfoService.getOne(stuWrapper);

        if (borrowCardInfo == null){
            return null;
        }
        BeanUtils.copyProperties(borrowCardInfo,result);
        BeanUtils.copyProperties(stuInfo,result);
        System.out.println(result);
        return result;
    }

    /**
     * 删除认证消息
     * @param userId
     */
    @Override
    public void delCertificateInfo(String userId) {
        UserInfo userInfo = new UserInfo();
        userInfo.setStatus(0);
        userInfo.setId(userId);
        baseMapper.updateById(userInfo);

        QueryWrapper<BorrowCardInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id",userId);
        borrowCardInfoService.remove(wrapper1);

        QueryWrapper<StuInfo> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("user_id",userId);
        stuInfoService.remove(wrapper2);
    }

    /**
     * 多条件分页查询，只完成认证状态(未认证、已认证)条件查询，可扩展
     *  TODO
     * @param current
     * @param limit
     * @param borrowCardInfoVo
     * @return
     */
    @Override
    public Map<String, Object> getUserInfoList(long current, long limit, BorrowCardInfoVo borrowCardInfoVo) {
        HashMap<String, Object> result = new HashMap<>();
        List<UserInfoVo> userInfoVos = new ArrayList<>();
        UserInfoVo userInfoVo = new UserInfoVo();
        Page<BorrowCardInfo> page = new Page<>(current,limit);

        Page<UserInfo> userInfoPage = new Page<>(current,limit);
        QueryWrapper<BorrowCardInfo> wrapper = new QueryWrapper<>();

        if (borrowCardInfoVo.getAuthStatus()==null && borrowCardInfoVo.getStatus()==null){
            Page<UserInfo> userInfoPage1 = baseMapper.selectPage(userInfoPage,null);
            long pages = userInfoPage1.getPages();
            long size = userInfoPage1.getSize();
            long total = userInfoPage1.getTotal();
            List<UserInfo> userInfos = userInfoPage1.getRecords();
            for (UserInfo userInfo:userInfos){

                String userId=userInfo.getId();
                userInfoVo.setUserId(userId);
                BeanUtils.copyProperties(userInfo,userInfoVo);
                System.out.println("1==================");
                System.out.println(userInfoVo);
                if (userInfo.getStatus() == 0){
                    userInfoVo.setAuthStatus(0);
                    userInfoVos.add(userInfoVo);
                    userInfoVo = new UserInfoVo();
                    continue;
                }
                BorrowCardInfo borrowCardInfo =
                        borrowCardInfoService.getOne(new QueryWrapper<BorrowCardInfo>().eq("user_id",userId));

                BeanUtils.copyProperties(borrowCardInfo,userInfoVo);
                userInfoVo.setCardStatus(borrowCardInfo.getStatus());
                System.out.println("2==================");
                System.out.println(userInfoVo);
                StuInfo stuInfo =
                        stuInfoService.getOne(new QueryWrapper<StuInfo>().eq("user_id",userId));
                BeanUtils.copyProperties(stuInfo,userInfoVo);
                userInfoVo.setStuStatus(stuInfo.getStatus());
                System.out.println("3==================");
                System.out.println(userInfoVo);
                userInfoVos.add(userInfoVo);
                userInfoVo = new UserInfoVo();

            }
            result.put("total",total);
            result.put("size",size);
            result.put("pages",pages);
            result.put("records",userInfoVos);
            return result;
        }else if (borrowCardInfoVo.getAuthStatus()!=null &&borrowCardInfoVo.getStatus()==null){
            Page<UserInfo> userInfoPage1;
            if (borrowCardInfoVo.getAuthStatus() != 2){
                userInfoPage1 = baseMapper.selectPage(userInfoPage, new QueryWrapper<UserInfo>().eq("status", borrowCardInfoVo.getAuthStatus()));
            }else{
                userInfoPage1 = baseMapper.selectPage(userInfoPage, new QueryWrapper<UserInfo>().eq("status", borrowCardInfoVo.getAuthStatus()).or().eq("status",-2));
            }
            long pages = userInfoPage1.getPages();
            long size = userInfoPage1.getSize();
            long total = userInfoPage1.getTotal();
            List<UserInfo> userInfos = userInfoPage1.getRecords();
            for (UserInfo userInfo:userInfos){
                String userId=userInfo.getId();
                userInfoVo.setUserId(userId);

                BeanUtils.copyProperties(userInfo,userInfoVo);

                if (userInfo.getStatus() == 0){
                    userInfoVo.setAuthStatus(0);
                    userInfoVos.add(userInfoVo);
                    userInfoVo = new UserInfoVo();
                    continue;
                }

                BorrowCardInfo borrowCardInfo =
                        borrowCardInfoService.getOne(new QueryWrapper<BorrowCardInfo>().eq("user_id",userId));

                BeanUtils.copyProperties(borrowCardInfo,userInfoVo);
                userInfoVo.setCardStatus(borrowCardInfo.getStatus());
                StuInfo stuInfo =
                        stuInfoService.getOne(new QueryWrapper<StuInfo>().eq("user_id",userId));
                BeanUtils.copyProperties(stuInfo,userInfoVo);
                userInfoVo.setStuStatus(stuInfo.getStatus());
                userInfoVos.add(userInfoVo);
                userInfoVo = new UserInfoVo();

            }
            result.put("total",total);
            result.put("size",size);
            result.put("pages",pages);
            result.put("records",userInfoVos);
            return result;
        }else if (borrowCardInfoVo.getAuthStatus() == 2 &&borrowCardInfoVo.getStatus()==0){
            Page<UserInfo> userInfoPage1 = baseMapper.selectPage(userInfoPage, new QueryWrapper<UserInfo>().eq("status", -2));
            long pages = userInfoPage1.getPages();
            long size = userInfoPage1.getSize();
            long total = userInfoPage1.getTotal();
            List<UserInfo> userInfos = userInfoPage1.getRecords();
            for (UserInfo userInfo:userInfos){
                String userId=userInfo.getId();
                userInfoVo.setUserId(userId);

                BeanUtils.copyProperties(userInfo,userInfoVo);

                if (userInfo.getStatus() == 0){
                    userInfoVo.setAuthStatus(0);
                    userInfoVos.add(userInfoVo);
                    userInfoVo = new UserInfoVo();
                    continue;
                }

                BorrowCardInfo borrowCardInfo =
                        borrowCardInfoService.getOne(new QueryWrapper<BorrowCardInfo>().eq("user_id",userId));

                BeanUtils.copyProperties(borrowCardInfo,userInfoVo);
                userInfoVo.setCardStatus(borrowCardInfo.getStatus());
                StuInfo stuInfo =
                        stuInfoService.getOne(new QueryWrapper<StuInfo>().eq("user_id",userId));
                BeanUtils.copyProperties(stuInfo,userInfoVo);
                userInfoVo.setStuStatus(stuInfo.getStatus());
                userInfoVos.add(userInfoVo);

                userInfoVo = new UserInfoVo();

            }
            result.put("total",total);
            result.put("size",size);
            result.put("pages",pages);
            result.put("records",userInfoVos);
            return result;
        }else if (borrowCardInfoVo.getAuthStatus() == 2 &&borrowCardInfoVo.getStatus()==1){
            Page<UserInfo> userInfoPage1 = baseMapper.selectPage(userInfoPage, new QueryWrapper<UserInfo>().eq("status", 2));
            long pages = userInfoPage1.getPages();
            long size = userInfoPage1.getSize();
            long total = userInfoPage1.getTotal();
            List<UserInfo> userInfos = userInfoPage1.getRecords();
            for (UserInfo userInfo:userInfos){
                String userId=userInfo.getId();
                userInfoVo.setUserId(userId);

                BeanUtils.copyProperties(userInfo,userInfoVo);

                if (userInfo.getStatus() == 0){
                    userInfoVo.setAuthStatus(0);
                    userInfoVos.add(userInfoVo);
                    userInfoVo = new UserInfoVo();
                    continue;
                }

                BorrowCardInfo borrowCardInfo =
                        borrowCardInfoService.getOne(new QueryWrapper<BorrowCardInfo>().eq("user_id",userId));

                BeanUtils.copyProperties(borrowCardInfo,userInfoVo);
                userInfoVo.setCardStatus(borrowCardInfo.getStatus());
                StuInfo stuInfo =
                        stuInfoService.getOne(new QueryWrapper<StuInfo>().eq("user_id",userId));
                BeanUtils.copyProperties(stuInfo,userInfoVo);
                userInfoVo.setStuStatus(stuInfo.getStatus());
                userInfoVos.add(userInfoVo);

                userInfoVo = new UserInfoVo();

            }
            result.put("total",total);
            result.put("size",size);
            result.put("pages",pages);
            result.put("records",userInfoVos);
            return result;
        }

        return null;

    }


}
